﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;

namespace InstaMe
{
    public class FrameworkElementUtils
    {
        public static TClass FindElement<TClass>(DependencyObject aParent, string aName) where TClass : FrameworkElement
        {
            int iChildCount = VisualTreeHelper.GetChildrenCount(aParent);
            for (int iter = 0; iter < iChildCount; iter++)
            {
                DependencyObject iChildItem = VisualTreeHelper.GetChild(aParent, iter);
                if (iChildItem is FrameworkElement)
                {
                    FrameworkElement iChildElement = (FrameworkElement)iChildItem;
                    if (iChildElement is TClass)
                    {
                        if (String.IsNullOrEmpty(aName) || iChildElement.Name == aName)
                        {
                            return (TClass)iChildItem;
                        }                        
                    }
                    else
                    {
                        TClass iResult = FindElement<TClass>(iChildItem, aName);
                        if (iResult != null)
                        {
                            return iResult;
                        }
                    }
                }
                else
                {
                    TClass iResult = FindElement<TClass>(iChildItem, aName);
                    if (iResult != null)
                    {
                        return iResult;
                    }
                }                
            }
            return null;
        }
    }
}
